<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
header('Content-Type: text/html; charset=iso-8859-1');
global $USER, $CFG, $COURSE;
require_once('../../config.php');

$username = trim($_POST['username']);
$clave = $_POST['password'];
$oper = $_POST['oper'];
$curso = $_POST['curso'];
$txt_anuncio = $_POST['txt_anuncio'];
$postid = $_POST['post_id'];
$coment_rsa = $_POST['coment_rsa'];
$userid = $_POST["user"];

if( $oper == "login" && !empty ($username)  && !empty($clave) ){
    //$user = get_record("user","username",$username,"password" ,  md5($clave) );
    $user = get_record("user","username",$username );
    if($user){    
        $user = get_complete_user_data('username', $user->username);
        $USER = complete_user_login($user);      
         if( $user && $USER ){
                set_moodle_cookie($USER->username);
                $contexto = get_context_instance(CONTEXT_SYSTEM);
         }
         $mis_cursos = get_records_sql("select courseid as id, c.fullname from mdl_enrol_utpl as e, mdl_course as c where e.courseid = c.id and  pdoid = 208 and userid = $USER->id"); 
            $list = array();
            
            foreach($mis_cursos as $curso){
                $list[] = $curso->id;
            }
            $userdata = array( "id" => "$USER->id" , "name" => "$USER->firstname  $USER->lastname" , "city" => "$USER->city" , "picture" => "$CFG->wwwroot/user/pix.php?file=$USER->id/f1.jpg" , "no_mesg" => count(get_messages($USER->id,$list)) , "no_cursos" => count($mis_cursos) );
            $resp = array("error" => "none" , "userid" => "$USER->id" , "$USER->id" => $userdata, "wwwroot" => $CFG->wwwroot  );
            //echo json_encode($resp);
            /*echo '<ul data-role="listview" data-inset="true" data-count-theme="e">                             
                             <li data-role="list-divider">Bienvenido</p></li>
                             <div class="ui-grid-a">
                                    <div style="width: 15%" class="ui-block-a">
                                        <img src="'.$CFG->wwwroot.'/user/pix.php?file='. $USER->id.'/f1.jpg"  alt="Estudiante picture"/>
                                    </div>
                                    <div style="width: 75%" class="ui-block-b">
                                        <strong>'.$USER->firstname . $USER->lastname.'</strong>
                                        <h2>'.$USER->city.'</h2>
                                    </div>
                            </div><!-- /grid-a -->
                             <li><a href="#"><img height="25px" width="25px" src="imgs/user_info.png" alt="Info User" class="ui-li-icon">Perfil</a></li> 
                             <li><a data-transition="slide" href="#mensajes"><img height="25px" width="25px" src="imgs/mail.png" alt="Info User" class="ui-li-icon">  Mensajes<span class="ui-li-count">'.get_messages_total($USER->id,$list).'</span></a></li> 
                             <li><a data-transition="slide" href="#cursos_view"><img height="25px" width="25px" src="imgs/course_icon.png" alt="Info User" class="ui-li-icon">Cursos<span class="ui-li-count">'.count($mis_cursos).'</span></a>
                             </li>
                 </ul>';*/
        
    }else{
        $resp = array("error" => "No esta registrado" , "usuario" => $username , "nombre" => "" , "city" => "" , "picture" => "" , "no_mesg" => "0" , "no_cursos" => "0" );
        //echo json_encode($resp);
        //echo "0";
    }
    echo json_encode($resp);
}//end login


if( $oper == "save_anuncio" && !empty ($curso) && !empty($txt_anuncio)  ){
    /*
     * Primero se obtiene todas las secciones vacias donde es posible ingresar el anuncio
     */
    $anuncios = get_records_sql ("SELECT * FROM {$CFG->prefix}course_sections WHERE course = $curso AND section <> 0 AND summary = ''");
          $activo = true;
          foreach($anuncios as $anun){
              if($activo){
                  $anun_vacio = $anun;
                  $activo = false;
              }           
          }//end foreach
          
    $new_anuncio = get_record("course_sections","course",$curso,"section",$anun->section);
    if($new_anuncio){
        $new_anuncio->summary = $txt_anuncio;
        $new_anuncio->visible = '1';
        if(update_record("course_sections", $new_anuncio)){
            add_to_log($curso, "course", "editsection", "eva1/m/?anuncio=$new_anuncio->id", $anun->section, "0", $USER->id);
            echo '<li>
                        <p class="ui-li-aside"><strong>'.  get_fecha($new_anuncio->time) .'<strong></p><br>
                        <h3>'. utf8_decode($new_anuncio->summary).'</h3>
                        <br>
                        
                        '. get_comentarios_rsa($COURSE->id, $new_anuncio->id).'
                  </li>';
            
        }else{
            echo "No se pudo ingresar el anuncio";
        }
    }else{
        echo "No se pudo ingresar el anuncio";
    }
          
          
}//end guradar anuncio
/*$postid = $_POST['post_id'];
$coment_rsa*/ 

if( $oper == "save-coment-rsa" && !empty ($curso) && !empty($postid) && !empty($coment_rsa) && !empty($userid)  ){
    $post = get_record("rsa_post", "id", $postid  ,"courseid", $curso, "visible", "1");
    if($post){
        $rsa_post = new StdClass();
        $rsa_post->id = null;
        $rsa_post->post_id = $postid;
        $rsa_post->dequien = $userid;
        $rsa_post->paraquien = $post->user_id;
        $rsa_post->body = $coment_rsa;
        $rsa_post->stamp = time();
        $rsa_post->visible = "1";
        $rsa_post->courseid = $curso;
        $rsa_post->user_delete = "0";
        $rsa_post->ip = "";
        
        if($insert = insert_record("rsa_post_comentario", $rsa_post, true)){
           echo '<li>                                                             
                                <p>
                                    <img src="'.$CFG->wwwroot.'/user/pix.php?file='.$userid.'/f1.jpg"  alt="Estudiante picture">
                                   '.  get_nombres($userid) .'
                                   <p>'. utf8_decode($coment_rsa) .'</p>
                                </p>                                    
                                <span class="ui-li-count">'.  get_fecha($rsa_post->stamp) .'</span>
                            </li>';   
        }else{
            echo "No se pudo ingresar el comentario debido a un error";
        }
        
    }else{
        echo "Ocurrio un error al insertar el comentario rsa";
    }
}//end save comentario


function get_messages($receptor, $cursos){
    /*
     * Obtiene los mensajes por curso
     */

    
    $users = get_records_sql("SELECT r.id as id_sms,u.id, u.firstname, u.lastname, u.picture, u.imagealt, u.lastaccess,r.timecreated ,
                                                count(r.id) as messagecount, timecreated, ma.courseid
                                                FROM mdl_message r, mdl_message_answered ma, mdl_user u

                                                WHERE u.id = r.useridfrom 
                                                        AND ma.messageid = r.id 

                                                        AND r.useridto = {$receptor}
                                                        AND ma.messageanswerid = 0  AND ma.courseid in (1,2," .implode(",",$cursos).")
                                                GROUP BY u.id, u.firstname, u.lastname, u.picture, u.imagealt, u.lastaccess

                                                ORDER BY u.firstname ASC");
                                                        
   if($users){
       return $users;
       
   }else{
       return array();
   }
    
}//end get_messages

function get_teachers($curso){
    
   $managerroles = 3;
    $context = get_context_instance(CONTEXT_COURSE, $curso);
    $canseehidden =  has_capability('moodle/role:viewhiddenassigns', $context);

    $rusers = get_role_users($managerroles, $context,true, '', 'r.sortorder ASC, u.lastname ASC', $canseehidden);
    if( $rusers ){
        $datos_nm =array();

        foreach($rusers as $profe){
            if( $profe->firstname != "nn"){

                $datos_nm [] = array("id" => $profe->id ,"name" => strtoupper(utf8_decode($profe->firstname . " " .$profe->lastname)) , "mail" => $profe->email , "ciudad" => $profe->city ) ;                                                 
            }
        }
    }
    
    return $datos_nm;
} //end function

function get_messages_total($receptor, $cursos){
    /*
     * Obtiene los mensajes por curso
     */
     
    
    /*$users = get_records_sql("SELECT r.id as id_sms,u.id, u.firstname, u.lastname, u.picture, u.imagealt, u.lastaccess,r.timecreated ,
                                                count(r.id) as messagecount, timecreated, ma.courseid
                                                FROM mdl_message r, mdl_message_answered ma, mdl_user u

                                                WHERE u.id = r.useridfrom 
                                                        AND ma.messageid = r.id 

                                                        AND r.useridto = {$receptor}
                                                        AND ma.messageanswerid = 0  AND ma.courseid in (1,2," .implode(",",$cursos).")
                                                GROUP BY u.id, u.firstname, u.lastname, u.picture, u.imagealt, u.lastaccess

                                                ORDER BY u.firstname ASC");
                                                        
   if($users){
       return $users;
       
   }else{
       return array();
   }*/
    
    echo  "SELECT r.id as id_sms,u.id, u.firstname, u.lastname, u.picture, u.imagealt, u.lastaccess,r.timecreated ,
                                                count(r.id) as messagecount, timecreated, ma.courseid
                                                FROM mdl_message r, mdl_message_answered ma, mdl_user u

                                                WHERE u.id = r.useridfrom 
                                                        AND ma.messageid = r.id 

                                                        AND r.useridto = {$receptor}
                                                        AND ma.messageanswerid = 0  AND ma.courseid in (1,2," .implode(",",$cursos).")
                                                GROUP BY u.id, u.firstname, u.lastname, u.picture, u.imagealt, u.lastaccess

                                                ORDER BY u.firstname ASC";
    
}//end get_messages


function get_comentarios_rsa($curso, $section){
    global $USER, $CFG, $COURSE;
    require_once('../../config.php');
     $sql = "SELECT
                post.id,
                post.user_id,
                post.courseid,
                post.id_Section,
                pc.dequien,
                pc.paraquien,
                pc.body,
                pc.stamp
            FROM
                mdl_rsa_post AS post ,
                mdl_rsa_post_comentario AS pc
            WHERE
                post.visible = 1 AND
                post.courseid = $curso AND
                post.id_Section = $section AND
                post.id = pc.post_id AND
                pc.visible = 1 AND
                pc.courseid = $curso";
    
    $comentarios = get_records_sql($sql);
    
    if( $comentarios ){
        /*$coment = '<div class="rsa">
                        <ul id="coments_rsa_'.$comentario->id.'" data-role="listview" data-divider-theme="b" data-inset="true" data-count-theme="e"> 
                            <li data-role="list-divider">Comentarios</p></li>';*/
        $header = true;
        foreach( $comentarios as $comentario){
            if($header){
                $coment = '<div class="rsa">
                        <ul id="coments_rsa_'.$comentario->id.'" data-role="listview" data-divider-theme="b" data-inset="true" data-count-theme="e"> 
                            <li data-role="list-divider">Comentarios</p></li>';
                $header = false;
            }
                $coment = '<div class="rsa">
                        <ul id="coments_rsa_'.$comentario->id.'" data-role="listview" data-divider-theme="b" data-inset="true" data-count-theme="e"> 
                            <li data-role="list-divider">Comentarios</p></li>';
                $coment .= '<li>                                                             
                                <p>
                                    <img src="'.$CFG->wwwroot.'/user/pix.php?file='.$comentario->dequien.'/f1.jpg"  alt="Estudiante picture">
                                   '.  get_nombres($comentario->dequien) .'
                                   <p>'. utf8_decode($comentario->body) .'</p>
                                </p>                                    
                                <span class="ui-li-count">'.  get_fecha($comentario->stamp) .'</span>
                            </li>';                                        
        }//end foreach
                $coment .= '<li>  
                                    
                                <p>
                                    <img src="'.$CFG->wwwroot.'/user/pix.php?file='.$USER->id.'/f1.jpg"  alt="Estudiante picture">
                                    <p>'.  get_nombres($USER->id) .'</p>  
                                    <textarea id="coment_txt_rsa_' . $comentario->id . '"  placeholder=""></textarea>
                                </p> 
                                <div data-role="controlgroup" >
                                  <a id="postid_'.$comentario->id.'_'.$USER->id.'" class="coments_btn_rsa" href="#" data-theme="b"  data-role="button">Aceptar</a>
                                  <a href="#"  data-role="button">Cancelar</a>
                                </div>
                            </li>'; 
                
             $coment .= ' </ul>
                     </div>';
             return  $coment;
    }else{
        return false;
    }

}

function get_nombres($userid){
    $usuario = get_record("user","id",$userid);
    
    if($usuario){
        $name = utf8_decode("$usuario->firstname $usuario->lastname");
        return "<h1>$name</h1>"; 
    }else{
        return "";
    }
    
}


function get_tareas($curso){
    $tareas = get_records("assignment","course",$curso);
    $ban = review_array($tareas);
    if($ban){
       return $tareas; 
    }else{
        return array();
    }
}//end tareas

function get_foros($curso){
    $foros = get_records("forum","course",$curso);
    $ban = review_array($foros);
    if($ban){
       return $foros; 
    }else{
        return array();
    }
    
}//end get_foros

function get_fecha( $timestamp ){
    $dias= array ("Domingo","Lunes", "Martes", "Miércoles","Jueves", "Viernes", "Sábado");
    $meses = array("Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre");
    $dia_text = utf8_decode($dias[date("N",$timestamp)]);
    $mes_text = utf8_decode($meses[ date("m",$timestamp) * 1 ]);
    //return "$dia_text, ".date("j",$timestamp). " de (".date("m",$timestamp) .")  de ".date("o",$timestamp). " " . date("H:m",$timestamp) ;
    return "$dia_text, ".date("j",$timestamp). " de $mes_text de ".date("o",$timestamp). " " . date("H:m",$timestamp) ;
}

function review_array($objs){
     $ban = false;
     foreach($objs as $obj){
        if($obj->id != null){
            $ban = true;
        }
    }
    return  $ban;
}//end review_array

function es_profesor_curso($curso, $user){
    $resp = false;
    $profes = get_teachers($curso);
    if($profes){
        foreach($profes as $profe){
            if( $profe["id"] == $user){
               $resp = true; 
            }
        }
    }else{
        $resp = false;
    }
    return $resp;
}//end es_profesor_curso



function mobile_agent(){
    
}

?>
